package com.dd.logistics.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dd.logistics.entity.InboundOrder;
import com.dd.logistics.entity.Inventory;
import com.dd.logistics.entity.SupplierProduct;
import com.dd.logistics.mapper.InboundOrderMapper;
import com.dd.logistics.mapper.SupplierProductMapper;
import com.dd.logistics.service.InboundOrderService;
import com.dd.logistics.service.InventoryService;
import com.dd.logistics.service.SupplierService;
import com.dd.logistics.utils.OrderNumberGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
public class InboundOrderServiceImpl extends ServiceImpl<InboundOrderMapper, InboundOrder> implements InboundOrderService {
    
    @Autowired
    private InventoryService inventoryService;
    
    @Autowired
    private SupplierService supplierService;
    
    @Autowired
    private SupplierProductMapper supplierProductMapper;
    
    @Override
    public List<InboundOrder> getInboundOrderList() {
        QueryWrapper<InboundOrder> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("create_time");
        return this.list(wrapper);
    }
    
    @Override
    public Page<InboundOrder> getInboundOrderPage(Integer current, Integer size) {
        Page<InboundOrder> page = new Page<>(current, size);
        QueryWrapper<InboundOrder> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("create_time");
        return this.page(page, wrapper);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean confirmInbound(String orderNumber) {
        if (orderNumber == null || orderNumber.trim().isEmpty()) {
            throw new RuntimeException("入库单号不能为空");
        }
        
        try {
            // 查询入库单
            QueryWrapper<InboundOrder> wrapper = new QueryWrapper<>();
            wrapper.eq("order_number", orderNumber.trim());
            InboundOrder order = this.getOne(wrapper);
            if (order == null) {
                throw new RuntimeException("入库单不存在");
            }
            
            log.info("开始确认入库，入库单信息：订单号={}，供应商ID={}，商品编码={}，数量={}", 
                    order.getOrderNumber(), order.getSupplierId(), order.getProductCode(), order.getQuantity());
            
            // 检查状态
            if (order.getStatus() != InboundOrder.STATUS_PENDING) {
                throw new RuntimeException("入库单状态不正确，当前状态：" + order.getStatusName());
            }
            
            // 检查供应商是否存在
            if (!supplierService.checkSupplierExists(order.getSupplierId())) {
                throw new RuntimeException("供应商不存在，供应商ID：" + order.getSupplierId());
            }
            
            // 检查商品编码
            String productCode = order.getProductCode();
            if (productCode == null || productCode.trim().isEmpty()) {
                throw new RuntimeException("商品编码不能为空");
            }
            productCode = productCode.trim();
            
            // 验证商品编码是否存在
            QueryWrapper<SupplierProduct> productWrapper = new QueryWrapper<>();
            productWrapper.eq("product_code", productCode)
                         .eq("supplier_id", order.getSupplierId())
                         .eq("status", 1); // 只查询启用状态的商品
            
            log.info("开始查询商品信息，SQL条件：product_code={}，supplier_id={}", productCode, order.getSupplierId());
            SupplierProduct product = supplierProductMapper.selectOne(productWrapper);
            
            if (product == null) {
                // 尝试查找所有供应商的该商品编码
                QueryWrapper<SupplierProduct> allWrapper = new QueryWrapper<>();
                allWrapper.eq("product_code", productCode);
                List<SupplierProduct> allProducts = supplierProductMapper.selectList(allWrapper);
                
                if (allProducts.isEmpty()) {
                    throw new RuntimeException(String.format("商品编码[%s]不存在于系统中", productCode));
                } else {
                    throw new RuntimeException(String.format("商品编码[%s]不属于供应商[ID=%d]，该商品属于以下供应商：%s", 
                            productCode, order.getSupplierId(), 
                            allProducts.stream().map(p -> String.valueOf(p.getSupplierId())).collect(java.util.stream.Collectors.joining(","))));
                }
            }
            
            if (product.getStatus() != 1) {
                throw new RuntimeException(String.format("商品[编码=%s]已被禁用", productCode));
            }
            
            log.info("商品信息验证通过，商品ID={}，商品名称={}", product.getId(), product.getProductName());
            
            // 检查入库数量
            if (order.getQuantity() == null || order.getQuantity() <= 0) {
                throw new RuntimeException("入库数量必须大于0");
            }
            
            // 更新库存
            boolean success = inventoryService.updateQuantity(productCode, order.getQuantity());
            if (!success) {
                throw new RuntimeException("更新库存失败");
            }
            
            // 更新入库单状态
            order.setStatus(InboundOrder.STATUS_COMPLETED);
            success = this.updateById(order);
            if (!success) {
                throw new RuntimeException("更新入库单状态失败");
            }
            
            log.info("确认入库成功，入库单号：{}", orderNumber);
            return true;
        } catch (Exception e) {
            log.error("确认入库失败，入库单号：{}，原因：{}", orderNumber, e.getMessage(), e);
            throw new RuntimeException("确认入库失败：" + e.getMessage());
        }
    }
    
    @Override
    public boolean createInboundOrder(InboundOrder inboundOrder) {
        // 设置默认值
        inboundOrder.setOrderNumber(OrderNumberGenerator.generateInboundNumber());
        inboundOrder.setStatus(InboundOrder.STATUS_PENDING);
        
        // 验证数据
        if (inboundOrder.getSupplierId() == null) {
            throw new RuntimeException("供应商ID不能为空");
        }
        if (inboundOrder.getProductCode() == null || inboundOrder.getProductCode().trim().isEmpty()) {
            throw new RuntimeException("商品编码不能为空");
        }
        if (inboundOrder.getQuantity() == null || inboundOrder.getQuantity() <= 0) {
            throw new RuntimeException("入库数量必须大于0");
        }
        
        // 验证商品编码是否存在
        QueryWrapper<SupplierProduct> productWrapper = new QueryWrapper<>();
        productWrapper.eq("product_code", inboundOrder.getProductCode().trim())
                     .eq("supplier_id", inboundOrder.getSupplierId());
        SupplierProduct product = supplierProductMapper.selectOne(productWrapper);
        if (product == null) {
            throw new RuntimeException("商品编码不存在：" + inboundOrder.getProductCode());
        }
        
        return this.save(inboundOrder);
    }
} 